const vm = new Vue({
	el: '#app',
	delimiters: ['[[', ']]'],
	data: {
		username: getCookie('username'),
		carts: getCarts(),
		total_count: 0,
		total_selected_count: 0,
		total_selected_amount: 0,
		carts_tmp: [],
	},

	computed: {
		selected_all() {
			let selected = true;
			for (let i = 0; i < carts.length; i++) {
				if (carts[i].selected == false) {
					selected = false;
					break;
				}
			}

			return selected;
		}
	},

	mounted() {
		// 手动记录购物车的初始值，用于更新购物车失败时还原商品数量
		this.carts_tmp = JSON.parse(JSON.stringify(carts));
	},


	methods: {

		on_selected_all: function() {
			let selected = !this.selected_all;
			let url = '/carts/selection';
			axios.put(url, {
					selected
				}, {
					headers: {
						'X-CSRFToken': getCookie('csrftoken')
					},
					responseType: 'json',
					withCredentials: true
				})
				.then(response => {
					if (response.data.code == '0') {
						for (let i = 0; i < this.carts.length; i++) {
							this.carts[i].selected = selected;
							// 重新计算界面的价格和数量

						}
					} else {
						alert(response.data.errmsg);
					}
				})
				.catch(error => {
					console.log(error.response);

				})

		},

		update_selected: function(index) {
			let url = '/carts/';
			axios.put(url, {
					sku_id: this.carts[index].id,
					count: this.carts[index].count,
					selected: this.carts[index].selected
				}, {
					headers: {
						'X-CSRFToken': getCookie('csrftoken')
					},
					responseType: 'json',
					withCredentials: true
				})

				.then(response => {
					if (response.data.code == '0') {
						this.carts[index].selected = response.data.cart_sku.selected;
						// 重新计算界面的价格和数量

					} else {
						alert(response.data.errmsg);
					}
				}).catch(error => {
					console.log(error.response);
				})

		},
	}
});
